package com.apestech.api.condition.control;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.MakeCondition;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.util.callback.SpiltStrCallback;

public class ControlUtil extends StringUtil {

    public JSONObject getKeyInput(SqlSession session, String tab, String key, JSONObject input) throws Exception {
        JSONObject map=new JSONObject();
        MakeCondition con=new MakeCondition();
        execSplitStr(key, ",", new SpiltStrCallback() {
            @Override
            public void exec(String id) throws Exception {
                String SYS_NO_CHECK=input.getString("SYS_NO_CHECK");
                if(SYS_NO_CHECK!=null){
                    if((","+SYS_NO_CHECK+",").indexOf(","+id+",")<0 || input.get(id)!=null){
                        saveInputMap(session, tab, id, input, map, con);
                    }
                } else {
                    saveInputMap(session, tab, id, input, map, con);
                }
            }
        });
        saveInputMap(session, tab, "SYS_RQ", input, map, con);
        return map;
    }

    private void saveInputMap(SqlSession session, String tab, String key, JSONObject input, JSONObject output, MakeCondition con) throws Exception {
        Table table=session.getDictTable(tab);
        if(table==null) throw new Exception("请先生成执行表！");
        String fstart=session.getSpecialField().getStartDate();
        String fend=session.getSpecialField().getEndDate();
        if(table.getTreeTable(key)!=null) {
            con.addField(key, "PARENT", input.get(key), output);
            String treeid=input.getString("SYS_TREE_FIELD");
            if(treeid==null) treeid="";
            if((","+treeid+",").indexOf(","+key+",")<0){
                if(!"".equals(treeid)){
                    treeid=treeid+",";
                }
                treeid=treeid+key;
            }
            input.put("SYS_TREE_FIELD",treeid);
        } else if("SYS_RQ".equals(key)){
            if(input.get(key)!=null){
                con.addField(fstart, "LTE", input.get(key), output);
                con.addField(fend, "GTE", input.get(key), output);
            }
        } else if(fstart.equals(key) && input.get(key)!=null){
            con.addField(fstart, "GTE", input.get(key), output);
        } else if(fend.equals(key) && input.get(key)!=null){
            con.addField(fend, "LTE", input.get(key), output);
        } else {
            if(input.get(key)!=null) output.put(key, input.get(key));
//            else output.put(key, null);
        }
    }

}
